package com.test.netty.niotest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) throws IOException {
        // 创建selector对象
        Selector selector = Selector.open();
        // 创建channel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // channel绑定一个监听端口
        ssc.socket().bind(new InetSocketAddress(6666), 1024);
        // 设置channel为非阻塞
        ssc.configureBlocking(false);
        // 注册channel到selector
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        // 循环等待客户端链接
        while(true) {
            if (selector.select(1000) <= 0) {
                // 无时间发生
                System.out.println("服务器等待了1秒，无连接。");
            } else {
                // 有事件发生，获取关注事件的集合
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                // 循环处理事件
                while(keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    // 根据事件做相应处理
                    if (key.isAcceptable()) {
                        // 允许连接
                        SocketChannel socketChannel = ssc.accept();
                        // 注册channel到selector
                        socketChannel.register(selector, SelectionKey.OP_READ + SelectionKey.OP_WRITE, ByteBuffer.allocate(1024));
                    }
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel)key.channel();
                        ByteBuffer buff = (ByteBuffer)key.attachment();
                        channel.read(buff);
                        byte[] bs = new byte[buff.limit()];
                        System.out.println(new String(bs, StandardCharsets.UTF_8));
                    }
                    if (key.isWritable()) {

                    }
                    if (key.isConnectable()) {

                    }
                    keyIterator.remove();
                }
            }
        }
    }
}
